package com.ny.view;

import com.ny.entity.Admin;
import com.ny.entity.Order;
import com.ny.entity.Product;
import com.ny.entity.Student;
import com.ny.service.AdminService;
import com.ny.service.ProductService;
import com.ny.service.StudentService;
import com.ny.service.impl.AdminServiceImpl;
import com.ny.service.impl.ProductServiceImpl;
import com.ny.service.impl.StudentServiceImpl;

import java.sql.SQLException;
import java.util.List;
import java.util.Scanner;

// 程序主入口
public class IndexView {
    // 静态私有化输入，接收键盘传值
    private static Scanner scanner = new Scanner(System.in);
    // 静态私有化服务层对象，不让外部访问同时不需要实例化
    private static StudentService studentService = new StudentServiceImpl();
    private static ProductService productService = new ProductServiceImpl();
    private static AdminService adminService = new AdminServiceImpl();

    public static void main(String[] args) throws SQLException {
        while (true) {
            System.out.println("\n=== 校园商品售卖管理系统 ===");
            System.out.println("1. 学生登录");
            System.out.println("2. 管理员登录");
            System.out.println("3. 学生注册");
            System.out.println("4. 退出系统");
            System.out.print("请选择: ");

            int choice = scanner.nextInt();
            scanner.nextLine(); // 消耗换行符

            switch (choice) {
                case 1:
                    studentLogin();
                    break;
                case 2:
                    adminLogin();
                    break;
                case 3:
                    studentRegister();
                    break;
                case 4:
                    System.out.println("感谢使用，再见！");
                    return;
                default:
                    System.out.println("无效选择，请重新输入");
            }
        }
    }

    // 学生注册功能（从IndexView整合而来）
    private static void studentRegister() {
        System.out.print("请输入用户名: ");
        String name = scanner.next();
        System.out.print("请输入密码: ");
        String password = scanner.next();
        System.out.print("请输入手机号码: ");
        String phone = scanner.next();

        Student student = new Student();
        student.setName(name);
        student.setPassword(password);
        student.setPhone(phone);

        try {
            int result = adminService.addStudent(student);
            if (result > 0) {
                System.out.println("注册成功！");
            } else {
                System.out.println("注册失败");
            }
        } catch (Exception e) {
            System.out.println("注册过程中发生错误: " + e.getMessage());
        }
    }

    private static void studentLogin() throws SQLException {
        System.out.print("请输入用户名: ");
        String username = scanner.nextLine();
        System.out.print("请输入密码: ");
        String password = scanner.nextLine();

        try {
            Student student = studentService.selectStudent(username, password);
            if (student != null) {
                System.out.println("登录成功!");
                studentMenu(student);
            } else {
                System.out.println("用户名或密码错误!");
            }
        } catch (SQLException e) {
            System.out.println("登录失败: " + e.getMessage());
        }
    }

    private static void studentMenu(Student student) throws SQLException {
        while (true) {
            System.out.println("\n=== 学生菜单 ===");
            System.out.println("1. 查看商品列表");
            System.out.println("2. 购买商品");
            System.out.println("3. 查看我的订单");
            System.out.println("4. 修改个人信息");
            System.out.println("5. 退出");
            System.out.print("请选择: ");

            int choice = scanner.nextInt();
            scanner.nextLine(); // 消耗换行符

            switch (choice) {
                case 1:
                    showProducts();
                    break;
                case 2:
                    purchaseProduct(student.getStudentId());
                    break;
                case 3:
                    showStudentOrders(student.getStudentId());
                    break;
                case 4:
                    updateStudentInfo(student);
                    break;
                case 5:
                    return;
                default:
                    System.out.println("无效选择");
            }
        }
    }

    private static void showProducts() {
        try {
            List<Product> products = productService.getAllProducts();
            System.out.println("\n=== 商品列表 ===");
            for (Product product : products) {
                System.out.printf("ID: %d, 名称: %s, 价格: %.2f, 库存: %d, 描述: %s\n",
                        product.getProductId(), product.getName(),
                        product.getPrice(), product.getStock(),
                        product.getDescription());
            }
        } catch (SQLException e) {
            System.out.println("获取商品列表失败: " + e.getMessage());
        }
    }

    private static void purchaseProduct(int studentId) {
        showProducts();
        System.out.print("\n请输入要购买的商品ID: ");
        int productId = scanner.nextInt();
        System.out.print("请输入购买数量: ");
        int quantity = scanner.nextInt();
        scanner.nextLine(); // 消耗换行符

        try {
            boolean success = productService.purchaseProduct(studentId, productId, quantity);
            if (success) {
                System.out.println("购买成功!");
            } else {
                System.out.println("购买失败，可能是库存不足或商品不存在");
            }
        } catch (SQLException e) {
            System.out.println("购买失败: " + e.getMessage());
        }
    }

    private static void showStudentOrders(int studentId) throws SQLException {
        List<Order> orders = productService.getOrdersByStudentId(studentId);
        System.out.println("\n=== 我的订单 ===");
        for (Order order : orders) {
            System.out.printf("订单ID: %d, 商品ID: %d, 数量: %d, 总价: %.2f\n",
                    order.getOrderId(), order.getProductId(),
                    order.getNumber(), order.getTotalPrice());
        }
    }

    private static void updateStudentInfo(Student student) throws SQLException {
        System.out.print("请输入新用户名: ");
        String name = scanner.nextLine();
        System.out.print("请输入新电话: ");
        String phone = scanner.nextLine();
        System.out.print("请输入新密码: ");
        String password = scanner.nextLine();

        student.setName(name);
        student.setPhone(phone);
        student.setPassword(password);

        int result = studentService.updateStudent(student);
        if (result > 0) {
            System.out.println("个人信息更新成功!");
        } else {
            System.out.println("个人信息更新失败");
        }
    }

    private static void adminLogin() {
        System.out.print("请输入管理员用户名: ");
        String username = scanner.nextLine();
        System.out.print("请输入密码: ");
        String password = scanner.nextLine();

        Admin admin = adminService.login(username, password);
        if (admin != null) {
            System.out.println("管理员登录成功!");
            adminMenu();
        } else {
            System.out.println("用户名或密码错误!");
        }
    }

    private static void adminMenu() {
        while (true) {
            System.out.println("\n=== 管理员菜单 ===");
            System.out.println("1. 管理学生");
            System.out.println("2. 管理商品");
            System.out.println("3. 管理订单");
            System.out.println("4. 退出");
            System.out.print("请选择: ");

            int choice = scanner.nextInt();
            scanner.nextLine(); // 消耗换行符

            switch (choice) {
                case 1:
                    manageStudents();
                    break;
                case 2:
                    manageProducts();
                    break;
                case 3:
                    manageOrders();
                    break;
                case 4:
                    return;
                default:
                    System.out.println("无效选择");
            }
        }
    }

    private static void manageOrders() {
        boolean finished = false;
        while (true) {
            System.out.println("\n=== 订单管理 ===");
            System.out.println("1. 查看所有订单");
            System.out.println("2. 删除订单");
            System.out.println("3. 返回上级菜单");
            System.out.print("请选择: ");

            int choice = scanner.nextInt();
            scanner.nextLine(); // 消耗换行符

            switch (choice) {
                case 1:
                    showAllOrders();
                    break;
                case 2:
                    deleteOrder();
                    break;
                case 3:
                    finished = true;
                    break;
                default:
                    System.out.println("无效选择");
            }
            if (finished) break;
        }
    }

    private static void manageStudents() {
        while (true) {
            System.out.println("\n=== 学生管理 ===");
            System.out.println("1. 查看所有学生");
            System.out.println("2. 添加学生");
            System.out.println("3. 修改学生信息");
            System.out.println("4. 删除学生");
            System.out.println("5. 返回上级菜单");
            System.out.print("请选择: ");

            int choice = scanner.nextInt();
            scanner.nextLine(); // 消耗换行符

            switch (choice) {
                case 1:
                    showAllStudents();
                    break;
                case 2:
                    addStudent();
                    break;
                case 3:
                    updateStudent();
                    break;
                case 4:
                    deleteStudent();
                    break;
                case 5:
                    return;
                default:
                    System.out.println("无效选择");
            }
        }
    }

    private static void showAllStudents() {
        List<Student> students = adminService.getAllStudents();
        System.out.println("\n=== 学生列表 ===");
        for (Student student : students) {
            System.out.printf("ID: %d, 姓名: %s, 电话: %s\n",
                    student.getStudentId(), student.getName(), student.getPhone());
        }
    }

    private static void addStudent() {
        System.out.print("请输入学生姓名: ");
        String name = scanner.nextLine();
        System.out.print("请输入学生电话: ");
        String phone = scanner.nextLine();
        System.out.print("请输入学生密码: ");
        String password = scanner.nextLine();

        Student student = new Student();
        student.setName(name);
        student.setPhone(phone);
        student.setPassword(password);

        int result = adminService.addStudent(student);
        if (result > 0) {
            System.out.println("添加学生成功!");
        } else {
            System.out.println("添加学生失败");
        }
    }

    private static void updateStudent() {
        showAllStudents();
        System.out.print("\n请输入要修改的学生ID: ");
        int studentId = scanner.nextInt();
        scanner.nextLine(); // 消耗换行符

        System.out.print("请输入新姓名: ");
        String name = scanner.nextLine();
        System.out.print("请输入新电话: ");
        String phone = scanner.nextLine();
        System.out.print("请输入新密码: ");
        String password = scanner.nextLine();

        Student student = new Student();
        student.setStudentId(studentId);
        student.setName(name);
        student.setPhone(phone);
        student.setPassword(password);

        int result = adminService.updateStudent(student);
        if (result > 0) {
            System.out.println("修改学生信息成功!");
        } else {
            System.out.println("修改学生信息失败");
        }
    }

    private static void deleteStudent() {
        showAllStudents();
        System.out.print("\n请输入要删除的学生ID: ");
        int studentId = scanner.nextInt();
        scanner.nextLine(); // 消耗换行符

        int result = adminService.deleteStudent(studentId);
        if (result > 0) {
            System.out.println("删除学生成功!");
        } else {
            System.out.println("删除学生失败");
        }
    }

    private static void manageProducts() {
        while (true) {
            System.out.println("\n=== 商品管理 ===");
            System.out.println("1. 查看所有商品");
            System.out.println("2. 添加商品");
            System.out.println("3. 修改商品信息");
            System.out.println("4. 删除商品");
            System.out.println("5. 返回上级菜单");
            System.out.print("请选择: ");

            int choice = scanner.nextInt();
            scanner.nextLine(); // 消耗换行符

            switch (choice) {
                case 1:
                    showAllProducts();
                    break;
                case 2:
                    addProduct();
                    break;
                case 3:
                    updateProduct();
                    break;
                case 4:
                    deleteProduct();
                    break;
                case 5:
                    return;
                default:
                    System.out.println("无效选择");
            }
        }
    }

    private static void showAllProducts() {
        try {
            List<Product> products = productService.getAllProducts();
            System.out.println("\n=== 商品列表 ===");
            for (Product product : products) {
                System.out.printf("ID: %d, 名称: %s, 价格: %.2f, 库存: %d, 描述: %s\n",
                        product.getProductId(), product.getName(),
                        product.getPrice(), product.getStock(),
                        product.getDescription());
            }
        } catch (SQLException e) {
            System.out.println("获取商品列表失败: " + e.getMessage());
        }
    }

    private static void addProduct() {
        System.out.print("请输入商品名称: ");
        String name = scanner.nextLine();
        System.out.print("请输入商品价格: ");
        double price = scanner.nextDouble();
        System.out.print("请输入商品库存: ");
        int stock = scanner.nextInt();
        scanner.nextLine(); // 消耗换行符
        System.out.print("请输入商品描述: ");
        String description = scanner.nextLine();

        Product product = new Product();
        product.setName(name);
        product.setPrice(price);
        product.setStock(stock);
        product.setDescription(description);

        int result = adminService.addProduct(product);
        if (result > 0) {
            System.out.println("添加商品成功!");
        } else {
            System.out.println("添加商品失败");
        }
    }

    private static void updateProduct() {
        showAllProducts();
        System.out.print("\n请输入要修改的商品ID: ");
        int productId = scanner.nextInt();
        scanner.nextLine(); // 消耗换行符

        System.out.print("请输入新名称: ");
        String name = scanner.nextLine();
        System.out.print("请输入新价格: ");
        double price = scanner.nextDouble();
        System.out.print("请输入新库存: ");
        int stock = scanner.nextInt();
        scanner.nextLine(); // 消耗换行符
        System.out.print("请输入新描述: ");
        String description = scanner.nextLine();

        Product product = new Product();
        product.setProductId(productId);
        product.setName(name);
        product.setPrice(price);
        product.setStock(stock);
        product.setDescription(description);

        int result = adminService.updateProduct(product);
        if (result > 0) {
            System.out.println("修改商品信息成功!");
        } else {
            System.out.println("修改商品信息失败");
        }
    }

    private static void deleteProduct() {
        showAllProducts();
        System.out.print("\n请输入要删除的商品ID: ");
        int productId = scanner.nextInt();
        scanner.nextLine(); // 消耗换行符

        int result = adminService.deleteProduct(productId);
        if (result > 0) {
            System.out.println("删除商品成功!");
        } else {
            System.out.println("删除商品失败");
        }
    }

    private static void showAllOrders() {
        List<Order> orders = adminService.getAllOrders();
        System.out.println("\n=== 订单列表 ===");
        for (Order order : orders) {
            System.out.printf("订单ID: %d, 学生ID: %d, 商品ID: %d, 数量: %d, 总价: %.2f\n",
                    order.getOrderId(), order.getStudentId(),
                    order.getProductId(), order.getNumber(),
                    order.getTotalPrice());
        }
    }

    private static void deleteOrder() {
        showAllOrders();
        System.out.print("\n请输入要删除的订单ID: ");
        int orderId = scanner.nextInt();
        scanner.nextLine(); // 消耗换行符

        int result = adminService.deleteOrder(orderId);
        if (result > 0) {
            System.out.println("删除订单成功!");
        } else {
            System.out.println("删除订单失败");
        }
    }
}